package io.bhex.app.trade.ui;

import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.trade.presenter.StopProfitLossPresenter;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.trade.futures.bean.FutureStopProfitLossInfo;
import io.bhex.sdk.trade.futures.bean.FuturesPositionOrder;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2020-01-03
 * 邮   箱：
 * 描   述：
 * ================================================
 */

public class StopProfitLossActivity extends BaseActivity<StopProfitLossPresenter, StopProfitLossPresenter.StopProfitLossUI> implements StopProfitLossPresenter.StopProfitLossUI, View.OnClickListener {
    private View stopProfitRela;
    private EditText stopProfitEdit;
    private View stopLossRela;
    private EditText stopLossEdit;
    private CompoundButton.OnCheckedChangeListener stopProfitCheckedChangeListener;
    private Button btnSubmit;
    private TextView stopProfitUnit;
    private TextView stopLossUnit;
    private FuturesPositionOrder currenHold;
    private CheckBox btnStopProfitSwitcher;
    private CheckBox btnStopLossSwitcher;
    private RadioButton radioBtnStopProfitPriceIndex;
    private RadioButton radioBtnStopProfitPriceMarket;
    private RadioButton radioBtnStopLossPriceIndex;
    private RadioButton radioBtnStopLossPriceMarket;
    private RadioButton radioBtnStopProfitCloseCanClose;
    private RadioButton radioBtnStopProfitCloseAll;
    private RadioButton radioBtnStopLossCloseCan;
    private RadioButton radioBtnStopLossCloseAll;
    private CompoundButton.OnCheckedChangeListener stopLossCheckedChangeListener;
    private RadioGroup stopProfitTriggerPriceTypeRadioGroup;
    private RadioGroup stopProfitCloseWayRadioGroup;
    private RadioGroup stopLossTriggerPriceTypeRadioGroup;
    private RadioGroup stopLossCloseWayRadioGroup;
    private int STOP_PROFIT_TRIGGER_PRICE_TYPE = 1; //默认指数价
    private int STOP_PROFIT_CLOSE_POSITION_TYPE = 0;    //止盈平仓类型 0-只平当前可平仓位  1-平所有仓位
    private int STOP_LOSS_TRIGGER_PRICE_TYPE = 1; //默认指数价
    private int STOP_LOSS_CLOSE_POSITION_TYPE = 0;    //止损平仓类型 0-只平当前可平仓位  1-平所有仓位
    private FutureStopProfitLossInfo currentStopInfo;

    @Override
    protected int getContentView() {
        return R.layout.activity_stop_profit_loss_layout;
    }

    @Override
    protected StopProfitLossPresenter createPresenter() {
        return new StopProfitLossPresenter();
    }

    @Override
    protected StopProfitLossPresenter.StopProfitLossUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        btnStopProfitSwitcher = viewFinder.find(R.id.btn_switcher_stop_profit);
        btnStopLossSwitcher = viewFinder.find(R.id.btn_switcher_stop_loss);

        stopProfitRela = viewFinder.find(R.id.stopProfitRela);
        stopProfitEdit = viewFinder.editText(R.id.stopProfitEdit);
        stopProfitUnit = viewFinder.textView(R.id.stopProfitUnit);
        stopProfitTriggerPriceTypeRadioGroup = viewFinder.find(R.id.stopProfitTriggerPriceTypeRadioGroup);
        stopProfitCloseWayRadioGroup = viewFinder.find(R.id.stopProfitCloseWayRadioGroup);
        radioBtnStopProfitPriceIndex = viewFinder.find(R.id.radio_stop_profit_price_index);
        radioBtnStopProfitPriceMarket = viewFinder.find(R.id.radio_stop_profit_price_market);
        radioBtnStopProfitCloseCanClose = viewFinder.find(R.id.radio_stop_profit_close_can_close);
        radioBtnStopProfitCloseAll = viewFinder.find(R.id.radio_stop_profit_close_all);


        stopLossRela = viewFinder.find(R.id.stopLossRela);
        stopLossEdit = viewFinder.editText(R.id.stopLossEdit);
        stopLossUnit = viewFinder.textView(R.id.stopLossUnit);

        stopLossTriggerPriceTypeRadioGroup = viewFinder.find(R.id.stopLossTriggerPriceTypeRadioGroup);
        stopLossCloseWayRadioGroup = viewFinder.find(R.id.stopLossCloseWayRadioGroup);

        radioBtnStopLossPriceIndex = viewFinder.find(R.id.radio_stop_loss_price_index);
        radioBtnStopLossPriceMarket = viewFinder.find(R.id.radio_stop_loss_price_market);
        radioBtnStopLossCloseCan = viewFinder.find(R.id.radio_stop_loss_close_can_close);
        radioBtnStopLossCloseAll = viewFinder.find(R.id.radio_stop_loss_close_all);

        btnSubmit = viewFinder.find(R.id.btnSubmit);

        stopProfitCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setStopProfitSwitcher(isChecked);
            }
        };

        stopLossCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setStopLossSwitcher(isChecked);
            }
        };
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        btnStopProfitSwitcher.setOnCheckedChangeListener(stopProfitCheckedChangeListener);
        btnSubmit.setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_profit_price_index_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_profit_price_market_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_profit_close_can_close_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_profit_close_all_tips).setOnClickListener(this);

        viewFinder.find(R.id.radio_stop_loss_price_index_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_loss_price_market_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_loss_close_can_close_tips).setOnClickListener(this);
        viewFinder.find(R.id.radio_stop_loss_close_all_tips).setOnClickListener(this);

        stopProfitTriggerPriceTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    //止盈触发价格条件类型 0-按最新价触发  1-按指数价触发 默认为1
                    case R.id.radio_stop_profit_price_index:
                        STOP_PROFIT_TRIGGER_PRICE_TYPE = 1;
                        break;
                    case R.id.radio_stop_profit_price_market:
                        STOP_PROFIT_TRIGGER_PRICE_TYPE = 0;
                        break;
                }

            }
        });
        stopProfitCloseWayRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    //止盈平仓类型 0-只平当前可平仓位  1-平所有仓位 默认为0
                    case R.id.radio_stop_profit_close_can_close:
                        STOP_PROFIT_CLOSE_POSITION_TYPE = 0;
                        break;
                    case R.id.radio_stop_profit_close_all:
                        STOP_PROFIT_CLOSE_POSITION_TYPE = 1;
                        break;
                }

            }
        });
        stopLossTriggerPriceTypeRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    //止盈触发价格条件类型 0-按最新价触发  1-按指数价触发 默认为1
                    case R.id.radio_stop_loss_price_index:
                        STOP_LOSS_TRIGGER_PRICE_TYPE = 1;
                        break;
                    case R.id.radio_stop_loss_price_market:
                        STOP_LOSS_TRIGGER_PRICE_TYPE = 0;
                        break;
                }

            }
        });
        stopLossCloseWayRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    //止盈平仓类型 0-只平当前可平仓位  1-平所有仓位 默认为0
                    case R.id.radio_stop_loss_close_can_close:
                        STOP_LOSS_CLOSE_POSITION_TYPE = 0;
                        break;
                    case R.id.radio_stop_loss_close_all:
                        STOP_LOSS_CLOSE_POSITION_TYPE = 1;
                        break;
                }

            }
        });


    }

    /**
     * 设置止盈开关
     * @param isChecked
     */
    private void setStopProfitSwitcher(boolean isChecked) {
        //止盈
        updatePageStopProfitStatus(isChecked, currentStopInfo);
}

    /**
     * 设置止损开关
     * @param isChecked
     */
    private void setStopLossSwitcher(boolean isChecked) {
        //止损
        updatePageStopLossStatus(isChecked,currentStopInfo);
    }

    @Override
    public void showHoldInfo(FuturesPositionOrder holdOrder) {
        currenHold = holdOrder;
        if (currenHold != null) {
            stopProfitUnit.setText(KlineUtils.getFuturesPriceUnit(holdOrder.getSymbolId()));
            stopLossUnit.setText(KlineUtils.getFuturesPriceUnit(holdOrder.getSymbolId()));
            CoinPairBean mCoinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(holdOrder.getSymbolId());
            if (mCoinPairBean == null) {
                ToastUtils.showShort(this.getResources().getString(R.string.string_data_exception));
                return;
            }
            String minPricePrecision = mCoinPairBean.getMinPricePrecision();
            int digitPrice = NumberUtils.calNumerCount(this, minPricePrecision);
            PointLengthFilter pricePointFilter = new PointLengthFilter();
            pricePointFilter.setDecimalLength(digitPrice);
            stopProfitEdit.setFilters(new InputFilter[]{pricePointFilter});
            stopLossEdit.setFilters(new InputFilter[]{pricePointFilter});
        }
    }

    @Override
    public void showStopProfitLossInfo(FutureStopProfitLossInfo response) {
        currentStopInfo = response;
        btnStopProfitSwitcher.setOnCheckedChangeListener(null);
        if (!response.isStopProfit()) {
            btnStopProfitSwitcher.setChecked(false);
            updatePageStopProfitStatus(false,null);
        }else{
            btnStopProfitSwitcher.setChecked(true);
            updatePageStopProfitStatus(true,response);
        }

        btnStopProfitSwitcher.setOnCheckedChangeListener(stopProfitCheckedChangeListener);

        btnStopLossSwitcher.setOnCheckedChangeListener(null);
        if (!response.isStopLoss()) {
            btnStopLossSwitcher.setChecked(false);
            updatePageStopLossStatus(false,null);
        }else{
            btnStopLossSwitcher.setChecked(true);
            updatePageStopLossStatus(true,response);
        }

        btnStopLossSwitcher.setOnCheckedChangeListener(stopLossCheckedChangeListener);

        stopProfitEdit.setText(response.getStopProfitPrice());
        stopLossEdit.setText(response.getStopLossPrice());
    }

    private void updatePageStopProfitStatus(boolean isOpenProfitSwitcher, FutureStopProfitLossInfo response) {
        if (isOpenProfitSwitcher) {
            stopProfitEdit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
            stopProfitRela.setBackgroundResource(R.drawable.bg_corner_gray_line);
            viewFinder.textView(R.id.stopProfitTriggerPriceType).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.textView(R.id.stopProfitCloseWay).setTextColor(SkinColorUtil.getDark(this));
            radioBtnStopProfitPriceIndex.setClickable(true);
            radioBtnStopProfitPriceMarket.setClickable(true);
            radioBtnStopProfitCloseCanClose.setClickable(true);
            radioBtnStopProfitCloseAll.setClickable(true);
            if (response != null && response.isStopProfit()) {
                stopProfitEdit.setText(response.getStopProfitPrice());
                stopProfitTriggerPriceTypeRadioGroup.check(response.getStopProfitTriggerConditionType()==1?R.id.radio_stop_profit_price_index:R.id.radio_stop_profit_price_market);
                stopProfitCloseWayRadioGroup.check(response.getStopProfitCloseType()==0?R.id.radio_stop_profit_close_can_close:R.id.radio_stop_profit_close_all);
            }else{
                stopProfitTriggerPriceTypeRadioGroup.check(R.id.radio_stop_profit_price_index);
                stopProfitCloseWayRadioGroup.check(R.id.radio_stop_profit_close_can_close);
            }
        }else{
            stopProfitEdit.setInputType(InputType.TYPE_NULL);
            stopProfitEdit.setText("");
            stopProfitRela.setBackgroundResource(R.drawable.bg_corner_gray);
            viewFinder.textView(R.id.stopProfitTriggerPriceType).setTextColor(SkinColorUtil.getDark50(this));
            viewFinder.textView(R.id.stopProfitCloseWay).setTextColor(SkinColorUtil.getDark50(this));
            radioBtnStopProfitPriceIndex.setClickable(false);
            radioBtnStopProfitPriceMarket.setClickable(false);
            radioBtnStopProfitCloseCanClose.setClickable(false);
            radioBtnStopProfitCloseAll.setClickable(false);
            stopProfitTriggerPriceTypeRadioGroup.clearCheck();
            stopProfitCloseWayRadioGroup.clearCheck();
        }
    }

    private void updatePageStopLossStatus(boolean isOpenLossSwitcher, FutureStopProfitLossInfo response) {
        if (isOpenLossSwitcher) {
            stopLossEdit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
            stopLossRela.setBackgroundResource(R.drawable.bg_corner_gray_line);
            viewFinder.textView(R.id.stopLossTriggerPriceType).setTextColor(SkinColorUtil.getDark(this));
            viewFinder.textView(R.id.stopLossCloseWay).setTextColor(SkinColorUtil.getDark(this));
            radioBtnStopLossPriceIndex.setClickable(true);
            radioBtnStopLossPriceMarket.setClickable(true);
            radioBtnStopLossCloseCan.setClickable(true);
            radioBtnStopLossCloseAll.setClickable(true);
            if (response != null && response.isStopLoss()) {
                stopLossEdit.setText(response.getStopLossPrice());
                stopLossTriggerPriceTypeRadioGroup.check(response.getStopLossTriggerConditionType()==1?R.id.radio_stop_loss_price_index:R.id.radio_stop_loss_price_market);
                stopLossCloseWayRadioGroup.check(response.getStopLossCloseType()==0?R.id.radio_stop_loss_close_can_close:R.id.radio_stop_loss_close_all);
            }else{
                stopLossTriggerPriceTypeRadioGroup.check(R.id.radio_stop_loss_price_index);
                stopLossCloseWayRadioGroup.check(R.id.radio_stop_loss_close_can_close);
            }

        }else{
            stopLossEdit.setInputType(InputType.TYPE_NULL);
            stopLossEdit.setText("");
            stopLossRela.setBackgroundResource(R.drawable.bg_corner_gray);
            viewFinder.textView(R.id.stopLossTriggerPriceType).setTextColor(SkinColorUtil.getDark50(this));
            viewFinder.textView(R.id.stopLossCloseWay).setTextColor(SkinColorUtil.getDark50(this));
            radioBtnStopLossPriceIndex.setClickable(false);
            radioBtnStopLossPriceMarket.setClickable(false);
            radioBtnStopLossCloseCan.setClickable(false);
            radioBtnStopLossCloseAll.setClickable(false);
            stopLossTriggerPriceTypeRadioGroup.clearCheck();
            stopLossCloseWayRadioGroup.clearCheck();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnSubmit:
                String profitPrice = stopProfitEdit.getText().toString().trim();
                String lossPrice = stopLossEdit.getText().toString().trim();
                if (btnStopProfitSwitcher.isChecked()) {
                    if (TextUtils.isEmpty(profitPrice)) {
                        ToastUtils.showLong(getString(R.string.input_stop_profit_price));
                        return;
                    }
                }else{
                    profitPrice = "";   //关闭止盈
                }
                if (btnStopLossSwitcher.isChecked()) {
                    if (TextUtils.isEmpty(lossPrice)) {
                        ToastUtils.showLong(getString(R.string.input_stop_loss_price));
                        return;
                    }
                }else{
                    lossPrice = "";     //关闭止损
                }
                if (!btnStopProfitSwitcher.isChecked() && !btnStopLossSwitcher.isChecked()) {
                    getPresenter().closeStopProfitLoss();
                }else{
                    getPresenter().sumbitStopProfitLossPrice(profitPrice,STOP_PROFIT_TRIGGER_PRICE_TYPE,STOP_PROFIT_CLOSE_POSITION_TYPE,lossPrice,STOP_LOSS_TRIGGER_PRICE_TYPE,STOP_LOSS_CLOSE_POSITION_TYPE);
                }
                break;

            case R.id.radio_stop_profit_price_index_tips:
            case R.id.radio_stop_loss_price_index_tips:
                showDialogTips(getResources().getString(R.string.string_index_price),getResources().getString(R.string.string_stop_pl_index_price_tips));
                break;
            case R.id.radio_stop_profit_price_market_tips:
            case R.id.radio_stop_loss_price_market_tips:
                showDialogTips(getResources().getString(R.string.string_market_price_txt),getResources().getString(R.string.string_stop_pl_market_price_tips));
                break;
            case R.id.radio_stop_profit_close_can_close_tips:
            case R.id.radio_stop_loss_close_can_close_tips:
                showDialogTips(getResources().getString(R.string.string_can_close_position),getResources().getString(R.string.string_stop_pl_can_close_position_tips));
                break;
            case R.id.radio_stop_profit_close_all_tips:
            case R.id.radio_stop_loss_close_all_tips:
                showDialogTips(getResources().getString(R.string.string_all_position),getResources().getString(R.string.string_stop_pl_close_all_position_tips));
                break;

        }
    }

    /**
     * 弹出提示
     * @param title
     * @param tipsContent
     */
    private void showDialogTips(String title,String tipsContent) {
        DialogUtils.showDialogOneBtn(this, title, tipsContent, getResources().getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {

            }

            @Override
            public void onCancel() {

            }
        });

    }

    @Override
    public void closeStopProfitLoss(boolean isCloseSuccess) {
        finish();
//        updatePageStopProfitStatus(!isCloseSuccess, null);
//        if (!isCloseSuccess) {
            //开关状态重置之前状态
//            btnSwitcher.setOnCheckedChangeListener(null);
//            btnSwitcher.setChecked(true);
//            btnSwitcher.setOnCheckedChangeListener(stopProfitCheckedChangeListener);
//        }
    }
}
